package com.mes.handler;

import com.basis.utils.CodeGenerateRuleUtil;
import com.mes.data.EmesPBomItem;
import com.mes.manufacture.data.EmesoManuOrder;
import com.mes.manufacture.data.EmesoManuOrderBomItem;
import com.mes.manufacture.data.EmesoManuorderMaterial;
import com.wms.entity.WmsMaterialList;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.dal.service.OBQuery;
import org.openbravo.model.common.plm.ProductCategory;
import org.openbravo.model.common.uom.UOM;
import org.openbravo.model.common.uom.UOMConversion;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 生成备料清单
 */
public class GenerateMaterialHandler extends BaseActionHandler {

	public static final String RAWMATERIAL = "RAWMATERIAL";
	private static final Map<String, ProductCategory> m_map = new HashMap();

	@Override
	protected JSONObject execute(Map<String, Object> parameters, String content) {
		JSONObject jsonRep = new JSONObject();
		JSONObject result = null;
		String meg = "";
		try {
	        OBContext.setAdminMode();
			initMap();

			jsonRep.put("flag", true);
			jsonRep.put("message", "处理成功");

			if (m_map.size() == 0) {
				jsonRep.put("flag", false);
				jsonRep.put("message", "原材料类型不存在，请先维护原材料。");
				return jsonRep;
			}

			String jsonIds = new JSONObject(content).getString("ids");
			// 获取勾选的呼叫投料
			String[] ids = jsonIds.split("#####");

			EmesoManuOrder emo = null;

			for (String id : ids) {
				emo = OBDal.getInstance().get(EmesoManuOrder.class, id);
				if (emo.getGenerateStatus().equalsIgnoreCase("EXECUTED")) {
					meg += "【" + emo.getCode() + "的订单已经生成领料单】";
					continue;
				} else if (!emo.getStatus().equalsIgnoreCase("ISSUED")) {
					meg += "【" + emo.getCode() + "的订单不是已下达状态，无法生成备料清单】";
					continue;
				} else {
					WmsMaterialList emma = insertMaterialApplyBill(emo);
					result = insertMaterial(emo, emma);
					if (!result.getBoolean("flag")) {
						meg += result.getString("message");
					}
				}
			}
			if (!"".equalsIgnoreCase(meg)) {
				OBDal.getInstance().rollbackAndClose();
				jsonRep.put("flag", false);
				jsonRep.put("message", meg);
			} else {
				OBDal.getInstance().commitAndClose();
			}
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			e.printStackTrace();
		} finally {
			OBContext.restorePreviousMode();
		}

		return jsonRep;
	}

	/**
	 * 插入单计划备料清单
	 */
	private JSONObject insertMaterial(EmesoManuOrder emo, WmsMaterialList emma) {
		JSONObject result = new JSONObject();
		try {
			List<EmesoManuOrderBomItem> list = null;
			
			list = emo.getEmesoManuOrderBomItemList();

			for(EmesoManuOrderBomItem emob : list){
				if(emo.getProduct().getId().equalsIgnoreCase(emob.getProduct().getId())){
					continue;
				}
				UOM uomResult = getCountAndUom(emob);
					EmesoManuorderMaterial emm = new EmesoManuorderMaterial();
					emm.setProduct(emob.getProduct());
					emm.setUom(uomResult);
					BigDecimal qty = new BigDecimal(0);
					if(emob.getUom().getName().contains("/万")){
						qty = emo.getQty().divide(new BigDecimal(10000),5,BigDecimal.ROUND_HALF_DOWN).multiply(emob.getItemQty());
					}else{
						qty = emo.getQty().multiply(emob.getItemQty());
					}
					emm.setQty(qty);
					emm.setEmesoManuorder(emo);
					OBDal.getInstance().save(emm);
			}
			result.put("flag", true);
			result.put("message", "处理成功");
			emo.setGenerateStatus("EXECUTED");
			OBDal.getInstance().save(emo);
		} catch (Exception e) {
			try {
				result.put("flag", false);
				result.put("message", "处理失败");
			} catch (JSONException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 初始化原材料map
	 */
	private void initMap() {
		OBQuery query = OBDal.getInstance().createQuery(ProductCategory.class, "as e where e.searchKey = :value");
		query.setNamedParameter("value", RAWMATERIAL);
		ProductCategory pc = (ProductCategory) query.uniqueResult();
		m_map.put(RAWMATERIAL, pc);
	}

	/**
	 * 生成物料清单
	 */
	private void insertEMOMaterial(List<EmesPBomItem> list, BigDecimal pp, EmesoManuOrder emo, boolean flag,
			WmsMaterialList emma) throws Exception {
		if (flag) {
			EmesoManuorderMaterial emm = new EmesoManuorderMaterial();
			emm.setProduct(emo.getProduct());
			emm.setQty(emo.getQty());
			emm.setEmesoManuorder(emo);
			OBDal.getInstance().save(emm);
		} else {
			for (EmesPBomItem o : list) {
				EmesoManuorderMaterial emm = new EmesoManuorderMaterial();
				emm.setProduct(o.getProduct());
//				if(!o.isStopExpan()){
//					if(o.getWeight() != null) {
//						emm.setWeight(o.getWeight().multiply(pp));
//					}
//				} else {
//					emm.setWeight(o.getWeight());
//				}
				emm.setQty(o.getItemQty().multiply(pp));
				emm.setEmesoManuorder(emo);
				OBDal.getInstance().save(emm);
			}
		}
	}
	
	/**
	 * 返回单位
	 * @param emob
	 * @return
	 */
	private UOM getCountAndUom(EmesoManuOrderBomItem emob){
		
		List<UOMConversion> list = new ArrayList();
		
		String ediStr = emob.getUom().getEDICode();
		
		if(ediStr.contains("/")){
			String [] uoms = ediStr.split("/");
			list = emob.getUom().getUOMConversionList();
			for(UOMConversion uc:list){
//				if(uoms[0].equalsIgnoreCase(uc.getToUOM().getEDICode())){
					return uc.getToUOM();
//				}
			}
		}else{
			return emob.getProduct().getUOM();
		}
		return null;
	}
	
	/**
	 * 生成领料申请单
	 * @return 
	 */
	private WmsMaterialList insertMaterialApplyBill(EmesoManuOrder emo) {
		WmsMaterialList materialList = new WmsMaterialList();
		String applayCode = CodeGenerateRuleUtil.getCode("Wms_Material_List", "Code");
		materialList.setCode(applayCode);
		materialList.setOrderCodes(emo.getCode());
		materialList.setOrganization(emo.getOrganization());
		materialList.setStatus("create");
		OBDal.getInstance().save(materialList);
		return materialList;
	}

}
